package com.ebuy.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.ebuy.factory.DBConnectionFactory;
import com.ebuy.model.Customer;
import com.mysql.jdbc.PreparedStatement;

public class CustomerDAO {

	private static final String CREATE_CUSTOMER = "INSERT INTO customer (name, username, password) VALUES (?,?,?);";
	private static final String GET_CUSTOMER = "SELECT * FROM customer WHERE username = ? AND password = ?";

	public void createCustomer(Customer customer) {
		Connection conn = DBConnectionFactory.getInstance().getConnection();

		try {
			PreparedStatement st = (PreparedStatement) conn
					.prepareStatement(CREATE_CUSTOMER);

			st.setString(1, customer.getName());
			st.setString(2, customer.getUsername());
			st.setString(3, customer.getPassword());

			st.executeUpdate();

			if (st != null) {
				st.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}
	}

	public Customer getSingleCustomer(String username, String password) {
		Connection conn = DBConnectionFactory.getInstance().getConnection();
		Customer c = null;
		try {
			PreparedStatement st = (PreparedStatement) conn
					.prepareStatement(GET_CUSTOMER);

			st.setString(1, username);
			st.setString(2, password);

			ResultSet rs = st.executeQuery();

			if (rs.next()) {
				c = new Customer();

				c.setName(rs.getString("name"));
				c.setUsername(rs.getString("username"));
				c.setPassword(rs.getString("password"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}
		return c;
	}

	public boolean validateCustomer(String username, String password) {
		if (this.getSingleCustomer(username, password) == null) {
			return false;
		} else {
			return true;
		}
	}
}
